'use strict'

function XcStorage($vue) {
  this.$vue = $vue
  this.MemCache = {}
}

function wrapKey(k) {
  return '_unistar_' + k
}

XcStorage.prototype.set = function (k, v) {
  this.MemCache[wrapKey(k)] = v
}

XcStorage.prototype.get = function (k) {
  return this.MemCache[wrapKey(k)] || ''
}

XcStorage.prototype.del = function (k) {
  delete this.MemCache[wrapKey(k)]
}

XcStorage.prototype.storeSet = function (k, v) {
  window.localStorage.setItem(wrapKey(k), v)
}

XcStorage.prototype.storeGet = function (k) {
  return window.localStorage.getItem(wrapKey(k)) || ''
}

XcStorage.prototype.storeDel = function (k) {
  window.localStorage.removeItem(wrapKey(k))
}

// ==================================
/**
 * 存储当前选择的空间
 */
XcStorage.prototype.setNamespace = function (ns) {
  this.set('namespace', ns)
  this.storeSet('namespace', ns)
}
/**
 * 获取当前选择的空间
 */
XcStorage.prototype.getNamespace = function () {
  let ns = this.get("namespace")
  if (!ns) ns = this.storeGet("namespace")
  return ns || 'DEFAULT_NS'
}

/**
 * 设置用户登录信息到内存
 * @param user 用户登录返回信息
 */
XcStorage.prototype.setUser = function (user) {
  let json = JSON.stringify(user)
  this.set("user", json)
  this.storeSet("user", json)
}

/**
 * 获取用户登录信息
 */
XcStorage.prototype.getUser = function () {
  let user = this.get("user") || ''
  if (!user) user = this.storeGet("user") || ''
  if (!user) return null
  return JSON.parse(user)
}

/**
 * 移除用户登录信息
 */
XcStorage.prototype.delUser = function () {
  this.del("user")
  this.storeDel("user")
}

/**
 * 检测用户是否有该角色权限
 */
XcStorage.prototype.checkUserRole = function (role) {
  let user = this.getUser() || {}
  let userRoles = user.roles || []
  // 全部可用
  if (!role) return true
  if ('ALL' === role) return true
  // 用户为超级管理员
  if (this.$vue.$collect.indexOf(userRoles, 'SUPER') !== -1) return true
  // 包含操作角色 
  return this.$vue.$collect.indexOf(userRoles, role) !== -1
}


/**
 * 是否登录
 */
XcStorage.prototype.checkLogin = function () {
  return !!this.getUser()
}

/**
 * 获取空间列表
 */
XcStorage.prototype.listNamespace = function (cb) {
  let namespaces = this.get('ns_list')
  if (!namespaces) {
    this.$vue.$md.dispatch('ns_list').then(data => {
      if (data.retCode === 1) {
        cb(data.data)
      } else {
        cb([])
      }
    })
  } else {
    cb(namespaces)
  }
}

/**
 * 移除缓存
 */
XcStorage.prototype.resetNamespace = function () {
  this.del('ns_list')
}

export default XcStorage